<?php

namespace app\middleware;

use Closure;

use think\Config;
use think\Request;
use think\Response;

class CorsMiddleware
{
    protected $cookieDomain;

    protected $header = [
        //'Access-Control-Allow-Origin' => '*', // *代表允许任何网址请求
        'Access-Control-Allow-Credentials' => 'true', // 设置是否允许发送 cookies
        'Access-Control-Max-Age' => 1800,
        'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS', // 允许请求的类型
        //'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With', // 设置允许自定义请求头的字段
        'Access-Control-Allow-Headers' => '*', // 支持头部带token字段
    ];

    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    /**
     * 允许跨域请求
     * @access public
     * @param Request $request
     * @param Closure $next
     * @param array $header
     * @return Response
     */
    public function handle($request, Closure $next, ?array $header = [])
    {
        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;

        if (!isset($header['Access-Control-Allow-Origin'])) {
            $origin = $request->header('origin');

            if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }

            /*
            $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
            $allow_origin = [
                'http://127.0.0.1:9527',
                'http://localhost:9527'
            ];
            if (in_array($origin, $allow_origin)) {
                header('Access-Control-Allow-Origin:' . $origin);
            }
            */
        }

        return $next($request)->header($header);
    }
}
